<template>
    <!-- Tab标签区域 -->
    <div class="tabs-container">
        <el-tabs v-model="tabsStore.activeTab.value" type="border-card" @tab-remove="removeTab" @tab-click="clickTab"
            class="demon-tabs">
            <el-tab-pane v-for="item in tabsStore.tabs.value" :key="item.path" :label="item.title" :name="item.path"
                :closable="item.path !== '/home'">
            </el-tab-pane>
            <!-- 主内容区 -->
            <el-main>
                <router-view v-slot="{ Component }">
                    <keep-alive>
                        <component :is="Component" />
                    </keep-alive>
                </router-view>
            </el-main>
        </el-tabs>
    </div>
</template>

<script setup>
import { watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useTabsStore } from '@/store/tabs'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const tabsStore = storeToRefs(useTabsStore())

// 移除Tab
const removeTab = (targetPath) => {
    const index = tabsStore.tabs.value.findIndex(tab => tab.path === targetPath)
    tabsStore.tabs.value.splice(index, 1)

    if (targetPath === tabsStore.activeTab.value) {
        const prevTab = tabsStore.tabs.value[index - 1] || tabsStore.tabs.value[0]
        if (prevTab) {
            router.push(prevTab.path)
        } else {
            router.push('/')
        }
    }
}

// 点击Tab
const clickTab = (tab) => {
    router.push(tab.paneName)
}

// 监听路由变化
watch(route, (newRoute) => {
    //导航路由如果为'/'则直接导航去'/home'以此保证首页默认为打开状态
    if (newRoute.path == '/')
        router.push('/home')

    tabsStore.activeTab.value = newRoute.path
    const currentTab = tabsStore.tabs.value.find(tab => tab.path === newRoute.path)
    if (currentTab && newRoute.meta?.title) {
        currentTab.title = newRoute.meta.title
    }
}, { immediate: true })
</script>

<style scoped>
.tabs-container {
    padding: 0px 20px 20px 20px;
    background-color: #fff;
    overflow: auto;
}


.el-main {
    padding: 0px;
    margin: 0px;
}
</style>